package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService flavorService;

    @Override
    @Transactional // 添加事务控制
    public void saveWithFlavors(DishDto dishDto) {
        //1. 保存菜品信息
        save(dishDto);

        //2. 保存口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> {
            // 设置口味对应的菜品dish_id
            dishFlavor.setDishId(dishDto.getId());
        });
        flavorService.saveBatch(flavors);
    }

    /**
     * 查询菜品和口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavors(Long id) {
        //1. 查询菜品信息
        Dish dish = getById(id);

        //2. 查询菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = flavorService.list(lqw);

        //3. 复制菜品数据到DishDto. 并添加口味
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    /**
     * 修改菜品和口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavors(DishDto dishDto) {
        //1. 修改菜品信息
        updateById(dishDto);

        //2. 删除之前菜品关联的口味数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        flavorService.remove(lqw);

        //3. 获取修改后的口味数据, 并且需要给口味设置dish_id
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
        });

        //4. 保存口味数据
        flavorService.saveBatch(flavors);
    }


}
